import Schema from 'async-validator'
import * as api from '@/api/user'
import { getStorage } from '@/utils/storage'
import { debounce } from '@/utils/debounce'
const appInstance = getApp()
Component({
  data: {
    values: {
      nickname: '',
      telephone: '',
      stuId: '',
      majorClass: '',
      selfIntroduction: ''
    },
    placeholders: {
      nickname: '请输入正确的姓名',
      telephone: '请输入正确的联系方式',
      stuId: '请输入正确的学号',
      majorClass: '请完成专业班级填写'
    },
    placeholderClass: {
      nickname: 'inp-font',
      telephone: 'inp-font' ,
      stuId: 'inp-font',
      majorClass: 'inp-font',
    },
    isValid: {
      nickname: '',
      telephone: '',
      stuId: '',
      majorClass: ''
    },
    // 性别
    sex: ["男", "女"],
    sexIndex: 0,
    // 学院
    collegeId: ["建筑与城市规划学院", "环境科学与工程学院", "外国语学院", "轻工化工学院", "物理与光电工程学院", "信息工程学院", "管理学院", "机电工程学院", "土木与交通工程学院", "体育学院", "法学院", "自动化学院", "商学院", "生物医药学院", "材料与能源学院","计算机学院", "艺术与设计学院", "数学与统计学院", "集成电路学院"],
    collegeIndex: 0,
    // 组别
    groupId: getStorage('group'),
    groupIndex: 0,
    // 年份
    year: ['2021', '2022', '2023', '2024', '2025'],
    yearIndex: 0,
    // 模态框与非模态框
    isModal: false,
    // 展示框
    isLoading: false,
    // 是否到时间
    isTime: appInstance.globalData.isTime,
    // 未到时间的toast
    loading: false,
    // 用于禁用提交按钮
    isSubmitting: false
  },
  methods: {
    validateInput(fieldName, value) {
      return new Promise((resolve, reject) => {
        const rules = {
          nickname: [
            { required: true, message: '请输入正确姓名' },
            { pattern: /^[\u4E00-\u9FA5]{2,10}(·[\u4E00-\u9FA5]{2,10}){0,2}$/, message: '请输入正确姓名' }
          ],
          telephone: [
            { required: true, message: '请输入正确的联系方式' },
            { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的联系方式' }
          ],
          stuId: [
            { required: true, message: '请输入正确的学号', },
            { pattern: /^[1-9]\d{9}$/, message: '请输入正确的学号', }
          ],
          majorClass: [
            { required: true, message: '请完成专业班级填写' }
          ],
        }

        const descriptor = {
          [fieldName]: rules[fieldName]
        }

        const validator = new Schema(descriptor)
        validator.validate({ [fieldName]: value }, (errors) => {
          if(!errors) {
            resolve(true)
          }else{
            resolve(false)
          }
        })
      })
    },
    checkIsValid() {
      for(const x in this.data.isValid) {
        if(this.data.isValid[x] !== true) {
          return false
        }
      }
      return true
    },
    handleInputChange(e) {
      const fieldName = e.currentTarget.dataset.name
      const value = e.detail.value
      this.validateInput(fieldName, value).then(valid => {
        if(valid) {
          this.setData({
            [`values.${fieldName}`]: value,
            [`placeholderClass.${fieldName}`]: 'warning',
            [`isValid.${fieldName}`]: true
          })
        }else{
          this.setData({
            [`values.${fieldName}`]: value,
            [`placeholderClass.${fieldName}`]: 'inp-font',
            [`isValid.${fieldName}`]: false
          })
        }
      })
    },
    //接受性别的字典值
    onSexChange(e) {
      const { index } = e.detail
      this.setData({
        sexIndex: index
      })
    },
    onCollegeChange(e) {
      const { index } = e.detail
      this.setData({
        collegeIndex: index
      })
    },
    onGroupChange(e) {
      const { index } = e.detail
      this.setData({
        groupIndex: index
      })
    },
    onYearChange(e) {
      const { index } = e.detail
      this.setData({
        yearIndex: index
      })
    },
    onInput(e) {
      const value = e.detail.value
      if(value.length > 300) {
        const trimValue = value.slice(0, 300)
        this.setData({
          'value.selfIntroduction': trimValue
        })
      }else{
        this.setData({
          'values.selfIntroduction': value
        })
      }
    },
    toast() {
      this.setData({
        loading: true
      })
      setTimeout(() => {
        this.setData({
          loading: false
        })
      }, 2000)
    },
    // 提交表单
    submitInfo() {
      if(this.checkIsValid()) {
        this.setData({
          isLoading: true,
          isModal: true
        })
      }
    },
    // 点击取消键
    cancel() {
      this.setData({
        isLoading: false
      })
    },
    // 点击确认键
    confirm: debounce(function() {
      const data = {
        id: '',
        sex: this.data.sexIndex == 0 ? false : true,
        nickname: this.data.values.nickname,
        stuId: this.data.values.stuId,
        groupId: Number(this.data.groupIndex) + 1,
        telephone: this.data.values.telephone,
        year: this.data.year[this.data.yearIndex],
        collegeId: Number(this.data.collegeIndex) + 1,
        majorClass: this.data.values.majorClass,
        selfIntroduction: this.data.values.selfIntroduction
      }
      api.reqRegister(data).then(res => {
        this.setData({
          isModal: false,
          isSubmitting: true
        })
        setTimeout(() => {
          this.setData({
            isLoading: false,
            isSubmitting: false
          })
          this.triggerEvent('mysubmit', true)
        }, 2000)
      })
    }, 300)
  }
})